package com.zzzfwd.menuhelper

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

class ConfigurationActivity : AppCompatActivity() {

    companion object {
        private const val CONFIGURATION_SHARED_PREF = "configuration_shared_pref"
    }

    private lateinit var menuViewModel: MenuViewModel
    private lateinit var adapter: ConfigurationAdapter
    private lateinit var configurations: ArrayList<Configuration>

    private val configurationView: RecyclerView by lazy { findViewById(R.id.configuration_view) }
    private val totalPriceEdit: EditText by lazy { findViewById(R.id.total_price_edit) }
    private val addBtn: Button by lazy { findViewById(R.id.add_btn) }
    private val saveBtn: Button by lazy { findViewById(R.id.save_btn) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_configuration)

        val sharedPreferences = getSharedPreferences(CONFIGURATION_SHARED_PREF, MODE_PRIVATE)
        menuViewModel =
            ViewModelProvider(
                this,
                MenuViewModelFactory(sharedPreferences)
            )[MenuViewModel::class.java]

        val confs = menuViewModel.getConfigurations()
        configurations = ArrayList(confs)

        adapter = ConfigurationAdapter(this, configurations)
        configurationView.adapter = adapter
        configurationView.layoutManager = LinearLayoutManager(this)

        val totalPrice = menuViewModel.getTotalPrice()
        totalPriceEdit.setText(totalPrice.toString())

        addBtn.setOnClickListener {
            configurations.add(Configuration(Dish("", 0, 0, 0), false))
            adapter.notifyItemInserted(configurations.size)
        }

        saveBtn.setOnClickListener {
            menuViewModel.saveConfigurations(configurations)
            val price = totalPriceEdit.text.toString().toIntOrNull() ?: 0
            val validationResult = menuViewModel.validateTotalPrice(configurations, price)
            if (validationResult.succeed) {
                menuViewModel.saveTotalPrice(price)
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(
                    this,
                    "总价应在[${validationResult.minPrice}, ${validationResult.maxPrice}]范围内",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
}